<template>
  <div class="createPost-container">
    <sticky :className="'sub-navbar'" :z-index="$upZindex">
      <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="back"  >{{$t('table.back')}}
      </el-button>
    </sticky>

    <el-form class="form-container" :model="postForm" :rules="rules" ref="postForm" label-position="right" label-width="170px" :style='form_style'>


      <div v-if="isMobile" class="divide-line-mobile">联系人信息</div>
      <div v-if="!isMobile" class="divide-line">联系人信息</div>

      <el-form-item label="供应商" prop="supplyName">
        {{postForm.supplyName}}
      </el-form-item>

      <el-form-item label="联系人" prop="linkNameId">
        {{postForm.linkName}}
      </el-form-item>

      <div v-if="isMobile" class="divide-line-mobile">具体沟通情况</div>
      <div v-if="!isMobile" class="divide-line">具体沟通情况</div>

      <el-form-item label="沟通时间" prop="commTime">
        {{postForm.commTime | $dateConvert("YYYY-MM-DD HH:mm:ss")}}
      </el-form-item>

      <el-form-item label="沟通状态" prop="status">
        {{postForm.status | validFilter}}
      </el-form-item>

      <el-form-item label="沟通方式" prop="commType">
        <el-tag v-for="(item,index) in postForm.commType" :key="index">{{item | $commTypeFilter}}</el-tag>
      </el-form-item>

      <el-form-item label="沟通目的" prop="commGoal">
        {{postForm.commGoal | $commGoalFilter}}
      </el-form-item>

      <el-form-item label="沟通进度" prop="commProgress">
        {{postForm.commProgress | $commProgressFilter}}
      </el-form-item>

      <el-form-item label="沟通难度" prop="commDifficulty">
        {{postForm.commDifficulty | $commDifficultyFilter}}
      </el-form-item>

      <el-form-item label="咔哒对接人" prop="objId">
        {{postForm.objName}}
      </el-form-item>

      <el-form-item label="沟通内容" prop="commContext">
        
        <el-input readonly="readOnly" type="textarea" v-model="postForm.commContext" placeholder="请输入"  style="width: 200px;" :autosize="{ minRows: 15}"></el-input>
      </el-form-item>

      <el-form-item label="沟通结果" prop="commResult">
         <el-input readonly="readOnly" type="textarea" v-model="postForm.commResult" placeholder="请输入"  style="width: 200px;" :autosize="{ minRows: 15}"></el-input>
      </el-form-item>

    </el-form>

    <div v-if="postForm.status=='T'" style="margin-bottom: 30px" align="center">
      <el-button v-has="'commTable_edit'" type="primary" size="large" @click="handleUpdate">{{$t('table.edit')}}沟通</el-button>
      <el-button v-has="'commTable_disable'" type="danger" size="large" @click="handleInvalid">{{$t('table.invalid')}}</el-button>
    </div>
  </div>
</template>

<script>
  // import Vue from 'vue'
  import Sticky from '@/components/Sticky' // 粘性header组件
  import { createCommunication, updateCommunication, fetchSupplyLinkManList, fetchLinkManList, infoCommunication, invalidCommunication } from '@/api/communication/communication'
  import { fetchSupplyList } from '@/api/util/util'
  import ImageCropper from '@/components/ImageCropper'
  import PanThumb from '@/components/PanThumb'
  import { isMobile } from '@/utils/mobile'
  const defaultForm = {
    code: ''
  }

  export default {
    name: 'communicationAdd',
    components: { Sticky, ImageCropper, PanThumb },
    data() {
      return {
        remnant: 200,
        imagecropperShow: false,
        imagecropperKey: 0,
        image: 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
        postForm: Object.assign({
          commType: []
        }, defaultForm),
        loading: false,
        rules: {

        },
        listQuery: {
          // supplyType: undefined,
          // status: undefined,
          // supplyLevel: undefined,
          // organizationType: undefined,
        },
        commTypeOptions: [{ label: '电话', key: 'TEL' }, { label: '拜访', key: 'VISIT' }, { label: '社交工具', key: 'SJ' }, { label: '邮件', key: 'MAIL' }, { label: '其他', key: 'OTHER' }],
        commGoalOptions: [{ label: '接洽', key: 'CONTACT' }, { label: '内容引入', key: 'CONTENT' }, { label: '内容输入', key: 'INPUT' }, { label: '商务交流', key: 'BUSINESS' }],
        commProgressOptions: [{ label: '待完成', key: 'WAIT' }, { label: '已完成', key: 'FINISH' }],
        commDifficultyOptions: [{ label: '一星', key: 'ONE' }, { label: '二星', key: 'TWO' }, { label: '三星', key: 'THREE' }, { label: '四星', key: 'FOUR' }, { label: '五星', key: 'FIVE' }],
        linkNameOptions: [],
        linkManOptions: [],
        isMobile: isMobile(),
        form_style: 'width: 60%; margin-left:10px;margin-top:20px;'
      }
    },
    filters: {
      validFilter(status) {
        const statusMap = {
          T: '已生效',
          F: '已失效'
        }
        return statusMap[status]
      }
    },
    computed: {
      contentShortLength() {
        return this.postForm.content_short.length
      }
    },
    created() {
      const id = this.$route.query.id
      console.info(this.isMobile)
      if (this.isMobile) {
        this.form_style = 'width: 60%; margin-left:-50px;margin-top:20px;'
      }
      if (id != null) {
        infoCommunication(id).then(response => {
          this.postForm = Object.assign({}, response.content) // copy obj
          // 沟通方式
          const commTypeStr = response.content.commType
          const commType = []
          const ranges = commTypeStr.split(',')
          for (var range in ranges) {
            commType.push(ranges[range])
          }
          this.postForm.commType = commType
          if (this.postForm.supplyId != null) {
            this.getSupplyLinkManList(this.postForm.supplyId)
          }
        })
      }
      this.getLinkManList()
    },
    methods: {
      querySearchAsync(queryString, callback) {
        var list = [{}]
        // 调用的后台接口
        // let url = 后台接口地址 + queryString;
        // 从后台获取到对象数组
        const params = { 'abbreviation': queryString }
        fetchSupplyList(params).then((response) => {
          // 在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
          for (const i of response.content) {
            // 将名字放入
            Object.assign(i, { 'value': i.abbreviation })
          }
          list = response.content
          callback(list)
        }).catch((error) => {
          console.log(error)
        })
      },
      // 供应商选择后的回调
      handleSelect(item) {
        // 供应商id
        this.postForm.supplyId = item.id
        // this.postForm.linkNameId = null;
        this.getSupplyLinkManList(this.postForm.supplyId)
      },
      getSupplyLinkManList(supplyId) {
        fetchSupplyLinkManList(supplyId).then((response) => {
          if (response.success) {
            this.linkNameOptions = []
            for (var a = 0; a < response.content.length; a++) {
              var aa = { label: response.content[a].linkName, key: response.content[a].id }
              this.linkNameOptions.push(aa)
            }
          }
        }).catch((error) => {
          console.log(error)
        })
      },
      getLinkManList() {
        this.listLoading = true
        fetchLinkManList().then(response => {
          if (response.success) {
            for (var a = 0; a < response.content.length; a++) {
              var aa = { label: response.content[a].userName, key: response.content[a].id }
              this.linkManOptions.push(aa)
            }
          }
        })
      },
      descInput() {
        var txtVal = this.postForm.background.length
        this.remnant = 200 - txtVal
      },
      cropSuccess(resData) {
        this.imagecropperShow = false
        this.imagecropperKey = this.imagecropperKey + 1
        this.image = resData.files.avatar
      },
      close() {
        this.imagecropperShow = false
      },
      submitForm() {
        this.$refs['postForm'].validate((valid) => {
          if (valid) {
            const commType = this.postForm.commType
            var commType_sub = ''
            // 拼接权限使用范围
            for (var i = 0; i < commType.length; i++) {
              var item = commType[i]
              if (item !== 'true') {
                commType_sub += item
                if (i !== commType.length - 1) {
                  commType_sub += ','
                }
              }
            }
            Object.assign(this.postForm, { 'commType': commType_sub })

            if (this.postForm.id != null) {
              updateCommunication(this.postForm).then(response => {
                if (response.success) {
                  this.$notify({
                    title: '成功',
                    message: '更新成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.push({ name: 'commTable' })
                }
              })
            } else {
              createCommunication(this.postForm).then((response) => {
                this.$notify({
                  message: '提交成功',
                  type: 'success',
                  duration: 2000
                })
                this.$router.push({ name: 'commTable' })
              })
            }
          }
        })
      },
      back() {
        // this.$router.push({ name: 'commTable' })
        history.go(-1)
      },
      // 更新页面
      handleUpdate() {
        this.$router.push({ name: 'commEdit', query: { id: this.$route.query.id }})
      },
      // 失效操作
      handleInvalid() {
        this.$confirm('失效后，该条数据不可操作，确认失效?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          // 调用删除接口
          var p = { id: this.$route.query.id }
          invalidCommunication(p).then(response => {
            if (response.success) {
              history.go(-1)
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
              this.$router.go(-1)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
    }
  }
</script>

<style scoped>
  .avatar{
    width: 200px;
    height: 200px;
    border-radius: 50%;
  }

    .el-textarea el-input--medium{
      width: 200px
    }
    .el-checkbox+.el-checkbox {
      margin-left: 10px;
  }

  .divide-line-mobile{
  width: 370px;
  padding: 0 20px 0;
  margin: 30px 30px;
  line-height: 3px;
  border-left: 130px solid #ddd;
  border-right: 100px solid #ddd;
  text-align: center;
  font-weight : bold;
}
</style>
